;(function ($){
	var count = 0;
	var roots_load = {};
	$.fn.loading = function(options) {
		if(!this.length)
			return this;
		var targetId = this.attr('id');
		if(!targetId){
			targetId = parseInt(Math.random()*10000000000);
			this.attr('id',targetId);
		}
		if(roots_load[targetId])
			return roots_load[targetId].self;
		else
			roots_load[targetId] = {
				self:this,
				count:0
			};

		var defaultOption = {
			backgroundImage: getPath()+"statics/images/common/loading.gif",
			msg: "正在操作中，请稍后。。。",
			zIndex:1000,
			container:$('body')//jquery对象容器
		};
		options = $.extend(defaultOption, options || {});
        var self = this;
		self.css({display: "none"});
		var loadBox = $("<div></div>").css({
			"position": "absolute",
			//"left": "25%",
			"background": "#ffffff",
			"box-shadow": "0px 0px 10px #666",
			"z-index": options.zIndex
		});
		var loadMsgDiv = $("<div></div>").css({
			"padding": "10px",
			"min-height": "30px"
		});
		var loadMsg = $("<span></span>").css({
			"background": "url('"+options.backgroundImage+"') center no-repeat",
			"display": "inline-block",
			"width": "30px",
			"height": "30px",
			"vertical-align": "middle",
			"padding-right": "10px"
		});
		var msg = $("<span>"+options.msg+"</span>");
		var loadBgDiv = $("<div></div>").css({
			"position": "absolute",
			"left": "0px",
			"top": "0px",
			"width": "100%",
			"height": "100%",
			"background": "#000",
			"opacity": "0.3",
			"filter": "alpha(opacity = 50)",
			"z-index": options.zIndex - 1
		});

		loadMsgDiv.append(loadMsg).append(msg).appendTo(loadBox);
		self.append(loadBox).append(loadBgDiv);
		options.container.append(self);

        self.showLoading = function () {
			self.css("display", "block");
			self.center();
			roots_load[targetId].count++;
			return self;
    	};
    	
        self.hideLoading = function () {
			if(roots_load[targetId].count > 0)
				roots_load[targetId].count--;
			if(roots_load[targetId].count == 0)
				self.css("display", "none");
			return self;
    	};

		self.clearLoading = function(){
			roots_load[targetId].count = 0;
			self.css("display", "none");
		};

		self.destroy = function(){
			roots_load[targetId] = null;
			self.css("display", "none");
			self.remove();
		};
    	
        self.center = function() {
    		var hei = options.container.outerHeight();
    		var wid = options.container.outerWidth();
    		var boxTop = (hei - loadBox.outerHeight()) / 2;
    		var boxLeft = (wid - loadBox.outerWidth()) / 2;
    		loadBox.css({"top": boxTop, "left": boxLeft});
    	};
        return self;
	}
})(jQuery);